package shop.controller.front.offlineAccount;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import shop.core.FrontBaseController;
import shop.core.Services;
import shop.core.common.bean.JSONResult;
import shop.core.util.DateTimeUtil;
import shop.services.front.account.bean.Account;
import shop.services.front.offline.OfflineService;
import shop.services.front.offline.bean.Offline;
import shop.services.front.offlineAccount.OfflineAccountService;
import shop.services.front.offlineAccount.bean.OfflineAccount;
import shop.services.front.retroactive.RetroactiveService;
import shop.services.front.retroactive.bean.Retroactive;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by wzl on 2017/8/7.
 */
@Controller
@RequestMapping("/front/offlineAccount")
public class OfflineAccountController extends FrontBaseController<OfflineAccount> {
    @Resource
    private OfflineAccountService offlineAccountService;
    @Resource
    private OfflineService offlineService;
    @Resource
    private RetroactiveService retroactiveService;

    @Override
    public Services<OfflineAccount> getService() {
        return offlineAccountService;
    }

    /**
     * 查询我参与的活动（已结束）
     *
     * @param offlineAccount
     * @return
     * @throws Exception
     */
    @RequestMapping("/selectOverList")
    @ResponseBody
    public JSONResult selectAllList(OfflineAccount offlineAccount) throws Exception {
        List<OfflineAccount> rsList = offlineAccountService.selectOverList(offlineAccount);
        jsonResult = new JSONResult();
        jsonResult.setData(rsList);
        return jsonResult;
    }

    /**
     * 查询活动参与者
     *
     * @param offlineAccount
     * @return
     * @throws Exception
     */
    @RequestMapping("/selectOfflineAccount")
    @ResponseBody
    public JSONResult selectOfflineAccount(OfflineAccount offlineAccount) throws Exception {
        List<OfflineAccount> rsList = offlineAccountService.selectListByOffline(offlineAccount);
        jsonResult = new JSONResult();
        jsonResult.setData(rsList);
        return jsonResult;
    }

    /**
     * 打卡方法
     *
     * @param offlineAccount 进行打卡的活动
     * @param request        用于获取登录用户
     * @return 请求结果
     */
    @RequestMapping("/signAccount")
    @ResponseBody
    public JSONResult signAccount(OfflineAccount offlineAccount, HttpServletRequest request) {
        jsonResult = new JSONResult();
        DateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Account loginAccount = (Account) request.getSession().getAttribute("accountInfo");
        if (loginAccount==null){
            return JSONResult.error("不是志愿者，无法打卡！");
        }
        offlineAccount.setAccountID(loginAccount.getId());
        offlineAccount = offlineAccountService.selectOne(offlineAccount);
//        判断用户是否参与活动
        if (offlineAccount != null) {
            Offline offline = offlineService.selectById(offlineAccount.getOfflineID());
            DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
            Date beginday=null;
            Date today=null;
            try {
                beginday=df.parse(offline.getBeginTime());
                today=new Date();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if(DateUtils.isSameDay(today, beginday)){
            int now = new Date().getHours();
            int beginTime = Integer.parseInt(offline.getBeginTimeFrame().split(":")[0].trim());
            int endTime = Integer.parseInt(offline.getEndTimeFrame().split(":")[0].trim());
//            判断是不是打卡时段  早于开始时间两小时 或者晚于结束时间两小时
            if (!((beginTime - now) < 2 && (beginTime - now) >= 0 || ((now - endTime) < 2 && (now - endTime) >= 0))) {
                return JSONResult.error("不是打卡时段");
            } else if ((beginTime - now) < 2&&(beginTime - now)>0 ) {
                //签到时段
//                判断是否已签到
                if (StringUtils.isBlank(offlineAccount.getSignInTime())) {
                    //未签到更新签到时间
                    offlineAccount.setSignInTime(f.format(new Date()));
                    offlineAccountService.update(offlineAccount);
                    offline.setCardRecord(offline.getCardRecord() + 1);//更新活动打卡次数
                    offlineService.update(offline);
                    return JSONResult.success("签到成功");
                }
//                已签到返回错误信息
                return JSONResult.error("不可重复签到");

            } else {//签退时段
//                判断是否已签退
                if (StringUtils.isBlank(offlineAccount.getSignOutTime())) {
//                    未签退更新签退时间
                    offlineAccount.setSignOutTime(f.format(new Date()));
                    offlineAccountService.update(offlineAccount);
                    offlineAccountService.update(offlineAccount);
                    offline.setCardRecord(offline.getCardRecord() + 1);//更新活动打卡次数
                    offlineService.update(offline);
                    return JSONResult.success("签退成功");
                }
//                已签退返回错误信息
                return JSONResult.error("不可重复签退");
            }
        }
            return JSONResult.error("不在打卡时段");
        }
        //未报名返回错误信息
        return JSONResult.error("您还未报名参加此次活动");
    }


    @RequestMapping(value = "/resign", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult resign(Retroactive retroactive, HttpServletRequest request) {
//        获取用户信息
        Account account = (Account) request.getSession().getAttribute("accountInfo");
        String accountId = account.getId();
//        获取用户参与活动信息
        OfflineAccount offlineAccount = new OfflineAccount();
        offlineAccount.setOfflineID(retroactive.getOfflineId());
        offlineAccount.setAccountID(accountId);
        offlineAccount = offlineAccountService.selectOne(offlineAccount);
//          判断用户是否参与活动
        if (offlineAccount != null) {
            Offline offline = offlineService.selectById(retroactive.getOfflineId());
            DateFormat f = new SimpleDateFormat("yyyy-MM-dd");
            Date endDate = null;
            try {
                endDate = f.parse(offline.getEndTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Date now = new Date();
            if (DateUtils.isSameDay(now, endDate)) {
                //同一天判断是否结束时间超过2小时
                int endtime = Integer.parseInt(offline.getEndTimeFrame().split(":")[0].trim());
                if ((now.getHours() - endtime) < 0)
                    return JSONResult.error("活动尚未结束，不可补签");
                else if ((now.getHours() - endtime) < 2 && retroactive.getSignType().equals("out"))
                    return JSONResult.error("尚在签退时段，请直接前往签退");
                //获取登录用户参与信息判断是否需要补签
                if (!check(offlineAccount, retroactive.getSignType())) {
                    if (retroactive.getSignType().equals("in"))
                        return JSONResult.error("已签到，无需申请补签到");
                    return JSONResult.error("已签退，无需申请补签退");
                }
                retroactive.setUserId(accountId);
                retroactiveService.insert(retroactive);
                 return JSONResult.success("申请成功,请耐心等待机构审核");

            }
//        不是同一天判断是否超过可补签时间
            if (DateTimeUtil.daysOfTwo(now, endDate) == 1) {
                int endtime = Integer.parseInt(offline.getEndTimeFrame().substring(0, 1));
                if ((now.getHours() - endtime) < 0) {
//                判断是否需要补签
                    if (!check(offlineAccount, retroactive.getSignType())) {
                        if (retroactive.getSignType().equals("in"))
                            return JSONResult.error("已签到，无需申请补签到");
                        return JSONResult.error("已签退，无需申请补签退");
                    }
                    retroactive.setUserId(accountId);
                    retroactiveService.insert(retroactive);
                    return JSONResult.success("申请成功,请耐心等待机构审核");

                }
            }
            return JSONResult.error("不在补签开放时间段");
        }
        return JSONResult.error("未参加该活动，不可申请补卡");
    }

    /**
     * 判断是否需要补签
     *
     * @param offlineAccount 补签活动参与信息
     * @param signType       补签类型
     * @return true：需要补签 false:不需要补签
     */
    private boolean check(OfflineAccount offlineAccount, String signType) {
        return ((signType.equals("out") && StringUtils.isBlank(offlineAccount.getSignOutTime())))
                || ((signType.equals("in") && StringUtils.isBlank(offlineAccount.getSignInTime())));
    }
}
